<template>
  <div class="search-form">
    <div class="title">
      <el-row justify="flex" align="center">
        <el-col :span="12" @click.native="handleChangeL" :class="{active:activeTab===0}">
          <i class="iconfont icondancheng"></i>
          <span>单程</span>
        </el-col>
        <el-col
          :span="12"
          class="tab"
          :class="{active:activeTab===1}"
          @click.native="handleChangeR"
        >
          <i class="iconfont iconshuangxiang"></i>
          <span>往返</span>
        </el-col>
      </el-row>
    </div>
    <el-form class="search-form-content" ref="form" label-width="80px" >
      <el-form-item label="出发城市">
        <!-- fetch-suggestions 返回输入建议的方法 -->
        <!-- select 点击选中建议项时触发 -->
        <el-autocomplete
          :fetch-suggestions="queryDepartSearch"
          placeholder="请搜索出发城市"
          class="el-autocomplete"
          v-model="cityInfo.departCity"
          @select="selectDepartCity"
          :trigger-on-focus="false"
          :highlight-first-item="true"
        >
          <template slot-scope="{ item }">
            <div >{{ item.value }}</div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="到达城市">
        <el-autocomplete
          :fetch-suggestions="queryDestSearch"
          placeholder="请搜索到达城市"
          class="el-autocomplete"
          v-model="cityInfo.destCity"
          @select="selectDestCity"
          :trigger-on-focus="false"
          :highlight-first-item="true"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="出发时间">
        <!-- change 用户确认选择日期时触发 -->
        <el-date-picker
          type="date"
          placeholder="请选择日期"
          style="width: 100%;"
          @change="changeDate"
          v-model="cityInfo.departDate"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label>
        <el-button style="width:100%;" type="primary" icon="el-icon-search" @click="submitSearch">搜索</el-button>
      </el-form-item>
      <div class="reverse">
        <span @click="reverseCity">换</span>
      </div>
    </el-form>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data () {
    return {
      activeTab: 0,
      currentTab: 0,
      cityInfo: {
        departCity: '',
        departCode: '',
        destCity: '',
        destCode: '',
        departDate: ''
      }
    }
  },
  created () {},
  mounted () {
  },
  methods: {
    handleChangeL () {
      this.activeTab = 0
    },
    handleChangeR () {
      this.activeTab = 1
      this.$confirm('暂时不提供往返功能?', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
    },
    // async getDepartList (depart, cb) {
    //   // if (!depart) return
    //   await this.$http.get('/airs/city', { params: { name: depart } }).then(res => {
    //     const { data } = res.data
    //     const newDepData = data.map(v => {
    //       return {
    //         ...v,
    //         value: v.name.replace(/市$/, '')
    //       }
    //     })
    //     const cityList = newDepData.filter(element => element.sort)
    //     this.newDepData = newDepData
    //     this.cityInfo.departCode = newDepData[0].sort
    //     this.cityInfo.departCity = newDepData[0].value
    //     this.newDepData = newDepData
    //     setTimeout(() => {
    //       cb(newDepData)
    //     }, 500)
    //     return cityList
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    // async getDestList (dest, cb) {
    //   console.log(dest)
    //   if (!dest) return
    //   await this.$http.get('/airs/city', { params: { name: dest } }).then(res => {
    //     const { data } = res.data
    //     const newDesData = data.map(v => {
    //       return {
    //         ...v,
    //         value: v.name.replace(/市$/, '')
    //       }
    //     })
    //     const cityList = newDesData.filter(element => element.sort)
    //     this.newDesData = newDesData
    //     this.cityInfo.destCode = newDesData[0].sort
    //     this.cityInfo.destCity = newDesData[0].value
    //     this.newDesData = newDesData
    //     setTimeout(() => {
    //       cb(newDesData)
    //     }, 500)

    //     return cityList
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    async queryDepartSearch (value, cb) {
      // console.log(value)
      const arr = await this.querySearchAsync(value)
      if (arr.length > 0) {
        // 不在下拉列表中选择，则默认选择第一项
        this.cityInfo.departCity = arr[0].value
        this.cityInfo.departCode = arr[0].sort
      }
      cb(arr)
    },

    // 目标城市输入框获得焦点时触发
    // value 是选中的值，cb是回调函数，接收要展示的列表
    async queryDestSearch (value, cb) {
      const arr = await this.querySearchAsync(value)
      if (arr.length > 0) {
        // 不在下拉列表中选择，则默认选择第一项
        this.cityInfo.destCity = arr[0].value
        this.cityInfo.destCode = arr[0].sort
      }
      cb(arr)
    },

    // 查询城市接口的方法，返回promise
    // queryString是查询关键字
    querySearchAsync (queryString) {
      console.log(queryString)
      return new Promise((resolve, reject) => {
        // 如果关键字是空，则直接返回
        if (!queryString) {
          return resolve([])
        }

        this.$http.get('/airs/city', { params: { name: queryString } }).then(res => {
          console.log(res)
          const { data } = res.data

          // 下拉提示列表必须要有value字段
          const arr = data.map(v => {
            return {
              ...v,
              value: v.name.replace('市', '')
            }
          })
          resolve(arr)
        })
      })
    },
    changeDate (date) {
      // eslint-disable-next-line no-undef
      this.cityInfo.departDate = moment(date).format('YYYY-MM-DD')
    },
    selectDepartCity (item) {
      console.log(this.newDepData)
      this.cityInfo.departCity = item.value
      this.cityInfo.departCode = item.sort
    },
    selectDestCity (item) {
      this.cityInfo.destCity = item.value
      this.cityInfo.destCode = item.sort
    },
    submitSearch () {
      const rules = {
        depart: {
          v: this.cityInfo.departCity,
          message: '请输入出发城市'
        },
        dest: {
          v: this.cityInfo.destCity,
          message: '请输入到达城市'
        },
        date: {
          v: this.cityInfo.departDate,
          message: '请输入出发时间'
        }
      }
      let valid = true
      Object.keys(rules).forEach(val => {
        console.log(rules)
        if (!valid) return
        if (!rules[val].v) {
          this.$message.warning(rules[val].message)
          valid = false
        }
      })

      if (!valid) return
      this.$router.push({
        path: '/plane/flight',
        query: this.cityInfo
      })

      const localAirs = JSON.parse(localStorage.getItem('airs') || '[]')

      localAirs.unshift(this.cityInfo)
      localStorage.setItem('airs', JSON.stringify(localAirs))
    },
    reverseCity () {
      const { departCity, departCode, destCity, destCode } = this.cityInfo
      // 交换出发地
      this.cityInfo.departCity = destCity
      this.cityInfo.departCode = destCode
      // 交换到达地
      this.cityInfo.destCity = departCity
      this.cityInfo.destCode = departCode
    }
  }
}
</script>

<style lang="less" scoped>
.search-form {
  text-align: center;
  height: 40px;
  line-height: 40px;
  background-color: #eee;
  .active {
    background-color: #fff;
    border-top: 2px solid orange;
  }
}
.search-form-content{
  padding:15px 50px 15px 15px;
  position: relative;

  .el-autocomplete{
    width: 100%;
  }
}

.reverse{
  position:absolute;
  top: 35px;
  right:15px;

  &:after,&:before{
      display: block;
      content: "";
      position: absolute;
      left:-35px;
      width:25px;
      height:1px;
      background:#ccc;
  }

  &:after{
      top:0;
    }

    &:before{
      top:60px;
    }

  span{
    display: block;
    position:absolute;
    top: 20px;
    right:0;
    font-size:12px;
    background: #999;
    color:#fff;
    width:20px;
    height:20px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;

    &:after,&:before{
      display: block;
      content: "";
      position: absolute;
      left:10px;
      width:1px;
      height:20px;
      background:#ccc;
    }

    &:after{
      top:-20px;
    }

    &:before{
      top:20px;
    }
  }
}
</style>
